var app = getApp();
const Zan = require('../../../dist/index');
const config = require('./config');
var Const = require('./../../../utils/const');
var mobile = null;

Page(Object.assign({}, Zan.TopTips, Zan.Field, {
	data: {
		type: null,
		hasLogin: false,
		isQuick: false,
		btnCodeText: '发送验证码',
		memberId: null,
		userinfoData: null,
		userinfoIv: null,
		mobileData: null,
		mobileIv: null,
		config,

		dialogOption: {
			dialogHidden: true,
			tipText: '微信授权',
		},
	},

	onLoad: function (options) {
		var that = this;

		if (options && options.type) {
			that.setData({
				type: options.type
			});
		}

		app.event.on("wx_auth", function () {
			that.setData({
				isQuick: true
			});
			if (!that.data.hasLogin) {
				// get userinfo
				app.wechat.checkSession().then(function () {
					that._login();
				}).catch(function (err) {
					that._login(true);
				});
			}
		})
	},

	onShow: function () {

	},

	changeType: function (e) {
		var that = this;
		var type = e.target.dataset.type;
		if (type == 1) {
			that.setData({
				isQuick: false
			});
		} else if (type == 2) {
			let wxAuth = wx.getStorageSync("wx_auth");
			if (!wxAuth) {
				// 需要授权登录
				this.setData({
					'dialogOption.dialogHidden' : false
				});
			} else {
				that.setData({
					isQuick: true
				});
				if (!that.data.hasLogin) {
					// get userinfo
					app.wechat.checkSession().then(function () {
						that._login();
					}).catch(function (err) {
						that._login(true);
					});
				}
			}
		}
	},

	mobileSubmit(e) {
		var that = this;
		var mobile = e.detail.value['login:mobile'];
		var code = e.detail.value['login:code'];

		//mobile check
		if (mobile != null && mobile != undefined && mobile != '') {
			if (!(/^1[3|4|5|7|8][0-9]\d{4,8}$/.test(mobile))) {
				that.showTopTips('请输入正确的手机号', {type: 'error'});
				return false;
			}
		} else {
			that.showTopTips('请输入手机号', {type: 'error'});
			return false;
		}

		//code check
		if (code != null && code != undefined && code != '') {
			if (!(/^\d{4}$/.test(code))) {
				that.showTopTips('请输入正确的验证码', {type: 'error'});
				return false;
			}
		} else {
			that.showTopTips('请输入验证码', {type: 'error'});
			return false;
		}

		var _data = {
			mobile: mobile,
			code: code
		};

		app.battery.common('login', _data)
			.then(function (data) {
				app.wechat.login().then(function (res) {
					if (res.code) {
						app.wechat.getUserInfo({lang: 'zh_CN'}).then(function (_res) {
							return app.battery.common('afterLogin', {
								code: res.code,
								ticket: data.ticket,
								userinfoData: _res.encryptedData,
								userinfoIv: _res.iv
							})
						}).then(function () {
							that.loginDataHandle(data);
						}).catch(function (err) {
							that.showTopTips(err.message, {type: 'error'});
						});
					} else {
						that.showTopTips('获取用户登录态失败！' + res.errMsg, {type: 'error'});
					}
				}).catch(function (e) {
					that.showTopTips(e.message, {type: 'error'});
				});
			})
			.catch(function (e) {
				that.showTopTips(e.errMsg, {type: 'error'});
			});
	},

	quickSubmit(e) {
		var that = this;

		app.wechat.checkSession().then(function () {
			console.log('----start quit login----');
			if (that.data.isRegister) {
				console.log('----quit register----');
				app.battery.common('qRegister', {
					id: that.data.memberId,
					mobileData: e.detail.encryptedData,
					mobileIv: e.detail.iv
				}).then(function (data) {
					that.loginDataHandle(data);
				}).catch(function (err) {
					that.showTopTips(err.message, {type: 'error'});
				});
			} else {
				console.log('----quit login----');
				app.battery.common('qLogin', {
					id: that.data.memberId
				}).then(function (data) {
					that.loginDataHandle(data);
				}).catch(function (err) {
					that.showTopTips(err.message, {type: 'error'});
				});
			}
		}).catch(function (err) {
			that._login();
		});

	},

	loginDataHandle: function (data) {
		var that = this;
		console.log(data);
		if (data.member) {
			that.showTopTips('成功', {type: 'success'});

			//save token
			app.data.token = data.ticket;
			app.data.member = data.member;
			app.wechat.setStorage(Const.DATA.KEY_TOKEN, data.ticket);
			app.wechat.setStorage(Const.DATA.KEY_MEMBER, data.member);

			if (that.data.type == 0) {
				// go back page
				wx.reLaunch({
					url: '/pages/index/index'
				})
			} else {
				// go back page
				wx.navigateBack({
					delta: 1
				})
			}
		} else {
			that.showTopTips(data.message, {type: 'warn'});
		}
	},

	checkboxChange: function (e) {
		var checked = e.detail.value
		var changed = {}
		for (var i = 0; i < this.data.checkboxItems.length; i++) {
			if (checked.indexOf(this.data.checkboxItems[i].name) !== -1) {
				changed['checkboxItems[' + i + '].checked'] = true
			} else {
				changed['checkboxItems[' + i + '].checked'] = false
			}
		}
		this.setData(changed)
	},

	radioChange: function (e) {
		var checked = e.detail.value
		var changed = {}
		for (var i = 0; i < this.data.radioItems.length; i++) {
			if (checked.indexOf(this.data.radioItems[i].name) !== -1) {
				changed['radioItems[' + i + '].checked'] = true
			} else {
				changed['radioItems[' + i + '].checked'] = false
			}
		}
		this.setData(changed)
	},

	_login: function (isUI, fn) {
		var that = this;
		console.log('----login----');
		app.wechat.login().then(function (res) {
			if (res.code) {
				//是否获取用户信息
				if (isUI) {
					console.log('----getUserInfo----');
					app.wechat.getUserInfo({lang: 'zh_CN'}).then(function (_res) {
						that.setData({
							userinfoData: _res.encryptedData,
							userinfoIv: _res.iv
						});
						console.log('----start req qPreLong----');
						//发起网络请求
						app.battery.common('qPreLogin', {
							code: res.code,
							userinfoData: _res.encryptedData,
							userinfoIv: _res.iv
						}).then(function (data) {
							console.log('----login success----');
							if (data.memberId) {
								if (data.temp == 0) {
									that.setData({
										memberId: data.memberId,
										hasLogin: true
									});
								} else {
									that.setData({
										isRegister: true,
										memberId: data.memberId,
										hasLogin: true
									});
								}
								fn && fn();
							} else {
								that.showTopTips(data.message, {type: 'error'});
							}
						});
					}).catch(function (err) {
						that.showTopTips(err.message, {type: 'error'});
					});
				} else {
					console.log('----not get UserInfo----');
					//发起网络请求
					app.battery.common('qPreLogin', {code: res.code}).then(function (data) {
						console.log('----qPreLogin success----');
						console.log(data, 222);
						if (data.memberId) {
							if (data.temp == 0) {
								that.setData({
									memberId: data.memberId,
									hasLogin: true
								});
							} else {
								that.setData({
									isRegister: true,
									memberId: data.memberId,
									hasLogin: true
								});
							}
							fn && fn();
						} else {
							that.showTopTips(data.message, {type: 'error'});
						}
					});
				}
			} else {
				that.showTopTips('获取用户登录态失败！' + res.errMsg, {type: 'error'});
			}
		}).catch(function (e) {
			that.showTopTips(e.message, {type: 'error'});
		});
	},

	getCode: function (event) {
		var that = this;
		if (!that.data.isCode) {
			//semd sms
			if (mobile != null && mobile != undefined && mobile != '') {
				if (!(/^1[3|4|5|7|8][0-9]\d{4,8}$/.test(mobile))) {
					that.showTopTips('请输入正确的手机号', {type: 'error'});
					return false;
				} else {
					app.battery.common('sendSmsCode', {mobile: mobile}).then(function (res) {
						that.showTopTips('发送成功', {type: 'success'});
					});
				}
			} else {
				that.showTopTips('请输入手机号', {type: 'error'});
				return false;
			}

			var seconds = 60;
			that.setData({
				isCode: true
			});
			countDown();

			function countDown() {
				if (seconds > 0) {
					seconds--;

					that.setData({
						btnCodeText: '重新发送(' + seconds + 's)'
					});
					setTimeout(function () {
						countDown();
					}, 1000);
				} else {
					that.setData({
						btnCodeText: '发送验证码',
						isCode: false
					});
				}
			}
		}
	},

	showTopTips(msg, params) {
		this.showZanTopTips(msg, params);
	},

	handleZanFieldChange(e) {
		const {componentId, detail} = e;
		mobile = e.detail.value;
	},

	handleZanFieldFocus(e) {
		const {componentId, detail} = e;
	},

	handleZanFieldBlur(e) {
		const {componentId, detail} = e;
	}
}));
